package com.itheima.controller;

import com.itheima.domain.User;
import com.itheima.service.UserService;
import com.itheima.service.impl.UserServiceImpl;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/user/*")
public class UserServlet extends BaseServlet {
    private UserService userService = new UserServiceImpl();
    //用户登录方法
    private void login(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        User user= userService.login(username, password);
            if(user!=null){
                //如果不为空则表示登录成功
                //将登录者的信息保存到session
                req.getSession().setAttribute("user",user);
                Cookie cookieName = new Cookie("username",user.getUsername());
                Cookie cookiePwd = new Cookie("password",user.getPassword());
                //获取复选框的值:1表示记住,其他表示没记住
                //boolean flags = false;
                String ck = req.getParameter("ck");
                //创建cookie对象
                if("1".equals(ck)){
                    //实现记住状态
                    //设置有效期
                    cookieName.setMaxAge(3600);
                    cookiePwd.setMaxAge(3600);
                    //flags = true;
                }else {
                    //设置有效期
                    cookieName.setMaxAge(0);
                    cookiePwd.setMaxAge(0);
                }
                //设置存储路径
                cookieName.setPath("/");
                cookiePwd.setPath("/");
                //添加到response对象
                resp.addCookie(cookieName);
                resp.addCookie(cookiePwd);
                //req.getSession().setAttribute("flags",flags);
                //登录成功重定向到首页
                resp.sendRedirect(req.getContextPath() + "/student/findAll");
            }else {
                //如果为空则表示登录失败
                //登录失败重定向到登录页面
                resp.sendRedirect(req.getContextPath()+"/login.jsp");
            }
        }

}
